package geektime.spring.springbucks.service;

import geektime.spring.springbucks.mapper.CoffeeMapper;
import geektime.spring.springbucks.model.Coffee;
import geektime.spring.springbucks.model.CoffeeExample;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Slf4j
@Service
public class CoffeeService {
    @Autowired
    private CoffeeMapper coffeeMapper;
    @Autowired
    private CoffeeService coffeeService;

    /**
     * 添加
     *
     * @param coffee
     */
    @Transactional
    public void saveCoffee(Coffee coffee) {
        coffeeMapper.insert(coffee);
    }

    /**
     * 查询
     *
     * @param name
     * @return
     */
    public List<Coffee> getCoffeesByCoffeeName(String name) {
        CoffeeExample example = new CoffeeExample();
        example.createCriteria().andNameLike("%"+name+"%");
        List<Coffee> list = coffeeMapper.selectByExample(example);
        list.forEach(e -> log.info("selectByExample: {}", e));
        return list;
    }

    /**
     * 更新coffee价格
     *
     * @param price
     * @param id
     * @return
     */
    @Transactional
    public void updateCoffeesPrice(float price, Long id) {
        Coffee coffee = new Coffee();
        coffee.setId(id);
        coffee.setPrice(Money.of(CurrencyUnit.of("CNY"), price));
        int count = coffeeMapper.updateByPrimaryKey(coffee);
        log.info("updateCoffeesPrice: {}", count);
    }


    /**
     * 批量添加
     *
     * @param coffeeList
     */
    @Transactional
    public void saveCoffeeList(List<Coffee> coffeeList) {
        for (Coffee tempCoffee : coffeeList) {
            coffeeService.saveCoffee(tempCoffee);
        }
    }

    /**
     * 批量查询
     *
     * @param ids
     * @return
     */
    public List<Coffee> getCoffeesByIDs(List<Long> ids) {
        CoffeeExample example = new CoffeeExample();
        example.createCriteria().andIdIn(ids);
        List<Coffee> list = coffeeMapper.selectByExample(example);
        list.forEach(e -> log.info("selectByExample: {}", e));
        return list;
    }

    /**
     * 分页查询coffee
     *
     * @param rowBounds
     * @return
     */
    public List<Coffee> selectCoffeePage(RowBounds rowBounds) {
        CoffeeExample example = new CoffeeExample();
        List<Coffee> list = coffeeMapper.selectByExampleWithRowbounds(example, rowBounds);
        list.forEach(e -> log.info("selectByExample: {}", e));
        return list;
    }


}
